/* SentenceController.java

{{IS_NOTE
	Purpose:
		
	Description:
		
	History:
		2009/8/7 �U�� 8:33:48 , Created by robbiecheng
}}IS_NOTE

Copyright (C) 2009 Potix Corporation. All Rights Reserved.

{{IS_RIGHT
	This program is distributed under GPL Version 2.0 in the hope that
	it will be useful, but WITHOUT ANY WARRANTY.
}}IS_RIGHT
 */
package org.corpus.english.controller;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.corpus.english.model.Sentence;
import org.corpus.english.model.SentenceHome;
import org.corpus.english.model.SentenceQuery;
import org.corpus.english.model.SentenceWordAnalysis;
import org.corpus.english.model.Word;
import org.corpus.english.model.WordHome;
import org.corpus.english.view.SentenceCategoryTreeNode;
import org.corpus.english.view.SentenceSourceTreeNode;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.Path;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.SelectEvent;
import org.zkoss.zk.ui.util.GenericForwardComposer;
import org.zkoss.zkplus.databind.AnnotateDataBinder;
import org.zkoss.zul.Div;
import org.zkoss.zul.Include;
import org.zkoss.zul.Tree;
import org.zkoss.zul.Treeitem;


/**
 * @author robbiecheng
 * 
 */
public class SentenceSearchController extends GenericForwardComposer {
	private SentenceHome dao = new SentenceHome();
	private WordHome wordDao = new WordHome();
	private SentenceQuery current =  new SentenceQuery();	
	
	public List getAllSentences(){
		return dao.findByExample(new Sentence());
	}
	

	/**
	 * @return the current
	 */
	public SentenceQuery getCurrent() {
		return current;
	}
	
	//save sentence sources into bean
	public void onSelect$source(SelectEvent evt){
		Set selectedItems = ((Tree)evt.getTarget()).getSelectedItems();
		HashSet sources = new HashSet(0);
		for (Iterator iterator = selectedItems.iterator(); iterator.hasNext();) {
			sources.add(((SentenceSourceTreeNode)((Treeitem)iterator.next()).getValue()).getValue());
		}
		current.setSentenceSourceDatas(sources);
	}
	//save sentence category into bean
	public void onSelect$category(SelectEvent evt){
		Set selectedItems = ((Tree)evt.getTarget()).getSelectedItems();
		HashSet categorys = new HashSet(0);
		for (Iterator iterator = selectedItems.iterator(); iterator.hasNext();) {
			categorys.add(((SentenceCategoryTreeNode)((Treeitem)iterator.next()).getValue()).getValue());
		}
		current.setSentenceCategoryDatas(categorys);
	}
	
	//search sentences
	private Div searchResult;
	public void onClick$searchBtn(){		
		UpdateManager.updateSearchResult(searchResult, UpdateManager.SENTENCE_SEARCH_RESULT, dao.findByQuery(current));
	}
	
	//sentence word analysis
	private Div wordAnalysis;
	public void onClick$wordAnalysisBtn(){		
		List sentences = dao.findByQuery(current);
		List words = new ArrayList();
		List results = new ArrayList();
		String commonWords = (String) Executions.getCurrent().getDesktop().getWebApp().getAttribute("commonwords");
		//word segmentation
		for (Iterator iterator = sentences.iterator(); iterator.hasNext();) {
			Sentence sent = (Sentence) iterator.next();
			String sourceName = sent.getSentenceSourceData().getFullname();
			if (sent.getContent() == null)
				continue;
			String content = sent.getContent();
			String clearContent = content.indexOf("\n") > -1 ? content.replaceAll("\n", "") : content;
			clearContent = clearContent.indexOf("\\p{Punct}") > -1 ? clearContent.replaceAll("\\p{Punct}", "") : clearContent;
			String[] wds = clearContent.split(" ");
			for (int i = 0; i < wds.length; i++) {
				if (commonWords.indexOf(wds[i]) > 0)
					continue;
				String[] wd = new String[2];
				wd[0] = wds[i];
				wd[1] = sourceName;
				words.add(wd);
			}
		}
		
		//sort word segmentation result
		Collections.sort(words, new wordComparator());
		
		//count word appearance
		String[] previous = null;
		int index = 0;
		int count = 1;
		String sources = "";
		for (Iterator iterator = words.iterator(); iterator.hasNext();) {
			if (previous == null) {
				if (words.size() == 1){
					String[] word = (String[])words.get(0);
					boolean existed = isWordExisted(word[0]);
					SentenceWordAnalysis result = new SentenceWordAnalysis(word[0], 
							count, word[1], existed);
					results.add(result);
				}
				previous = (String[]) iterator.next();
				sources+= previous[1];
				index++;
				continue;
			}
			String[] word = (String[]) iterator.next();
			index++;
			if (word[0].equals(previous[0])){
				count++;
				if (sources.indexOf(word[1]) < 0)
					sources+=(word[1]+",");
				if (index == words.size()) {
					boolean existed = isWordExisted(previous[0]);
					SentenceWordAnalysis result = new SentenceWordAnalysis(previous[0], 
							count, sources, existed);
					results.add(result);
				}
					
			} else {
				boolean existed = isWordExisted(previous[0]);
				SentenceWordAnalysis result = new SentenceWordAnalysis(previous[0], 
						count, sources.equals("")? previous[1]: sources, existed);
				results.add(result);
				if (index == words.size()) {
					boolean existed2 = isWordExisted(word[0]);
					SentenceWordAnalysis result2 = new SentenceWordAnalysis(word[0], 
							1, word[1], existed2);
					results.add(result2);
				}
				count = 1;
				sources = word[1]+",";
				previous = word;
			}
			
		}
		UpdateManager.updateSentenceWordAnalysis(wordAnalysis, UpdateManager.SENTENCE_WORD_ANALYSIS, results);
	}


	/**
	 * @param word
	 * @return
	 */
	private boolean isWordExisted(String word) {
		if (word == null)
			return false;		
		return !(wordDao.findByExample(new Word(word, true)).isEmpty());
	}

	//clear data	 
	public void onClick$clear(Event evt) {
		refresh();
	}
	private AnnotateDataBinder binder;
	public void onClick$resetBtn(Event evt) {
		current = new SentenceQuery();
		binder.loadAll();
	}
	private void refresh(){
		Include include = (Include) Path.getComponent("//index/sentence");
		include.invalidate();
	}
	
	class wordComparator implements Comparator {
		  public int compare(Object obj1, Object obj2) {
		    String[] wd1 = (String[])obj1;
		    String[] wd2 = (String[])obj2;
		    return wd1[0].compareTo(wd2[0].trim());
		  }
		}
	
	/**
	 * 
	 
	public void onClick$search(){
		SentenceQuery query = new SentenceQuery();
		query.setContent("234");
		
		Set sources = new HashSet();
		SentenceSourceData ssd1 = new SentenceSourceData();
		ssd1.setFullname("�r��");
		SentenceSourceData ssd2 = new SentenceSourceData();
		ssd2.setFullname("�ɰ���");
		
		sources.add(ssd1);
		sources.add(ssd2);
		query.setSentenceSourceDatas(sources);
		
		Set categorys = new HashSet();
		SentenceCategoryData scd1 = new SentenceCategoryData();
		scd1.setFullname("�ʵ�y��-����Vt.");
		SentenceCategoryData scd2 = new SentenceCategoryData();
		scd2.setFullname("�ʵ�y��-������Vt.");
		categorys.add(scd1);
		categorys.add(scd2);
		query.setSentenceCategoryDatas(categorys);
		
		dao.findByQuery(query);
	}*/

}
